package com.tuo51.foudation.exception;

import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.StatusResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletResponse;

import static com.tuo51.foudation.model.ErrorCode.FILE_SIZE_MORE_THAN_LIMIT;


/**
 * *******************************
 * Created by Ron.
 * form com.tuo51
 * on 2017/6/2
 * *******************************
 */
@ControllerAdvice
@Slf4j
public class GlobelExceptionHandler {

    @Value("${spring.profiles.active}")
    String env;

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody //在返回自定义相应类的情况下必须有，这是@ControllerAdvice注解的规定
    public StatusResponse exceptionHandler(RuntimeException e, HttpServletResponse response) {

        if (e instanceof BusinessException)
            return StatusResponse.error(((BusinessException) e).getErrorCode(), e.getMessage());

        e.printStackTrace();

        if (e instanceof MultipartException)
            return StatusResponse.error(FILE_SIZE_MORE_THAN_LIMIT, "文件过大！");

        if(env.equals("dev"))
            return StatusResponse.error(ErrorCode.UNDEFINED, e.getMessage());
        else
            return StatusResponse.undefined();
    }
}
